package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
public class LoginController {

    @Autowired
    private EmpService empService;

    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {
        log.info("员工登陆：{}",emp);
        Emp emp_return = empService.login(emp);

        //登陆成功，生成令牌，下发令牌
        if (emp_return != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", emp_return.getId());
            claims.put("name", emp_return.getName());
            claims.put("username", emp_return.getUsername());

            String jwt = JwtUtils.generateJwt(claims);
            return Result.success(jwt);
        }

        // 登录失败，返回错误信息
        return Result.error("用户名或者密码错误. . .");
    }
}
